const app = getApp()

import axios from '../../utils/axios'

Page({

  data: {
    showDel: false,
    startX: 0,
    startY: 0,
    couponState: false, // 优惠券模态框
    shoppList: [], // 购物车list
    allPitch: true, // 是否全选
    sumMoney: 0, // 合计
    sumCheap: 0, // 已优惠
    couponList: [], // 优惠券list
    deleteCartId: '', // 当前要删除的商品
    showLogin: false,
    allCount: 0, // 共计多少件商品
  },

  onLoad: function (options) {

    if (app.globalData.userToken == '') {
      this.setData({
        showLogin: true
      })
    }

    this.goodsCart()
    // this.getCoupon()
  },

  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      // shoppCountFlag为true时，说明有物品被加入购物车，需要重新刷新数量
      if (app.globalData.shoppCountFlag) {
        app.globalData.shoppCountFlag = false
        axios('/groupon/goodsCart').then(res => {
          if (res.data.resultcode == 1) {
            app.globalData.shoppCount = res.data.num
            this.getTabBar().setData({
              shoppCount: res.data.num
            })
          }
        })
      } else {
        this.getTabBar().setData({
          shoppCount: app.globalData.shoppCount
        })
      }
      this.getTabBar().setData({
        selected: 2
      })
    }
  },

  // 查询购物车
  goodsCart: function () {
    axios('/groupon/goodsCart').then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {

        let list = res.data.result

        let sumMoney = 0
        let sumCount = 0
        let showCheap = 0

        for (let i = 0, leng = list.length; i < leng; i++) {
          if (list[i].attach_id) {
            list[i]['cheap'] = list[i].attach_discount > 0.01 ? list[i].attach_price - list[i].attach_discount : 0
            list[i]['showMoney'] = list[i].attach_discount > 0.01 ? list[i].attach_discount : list[i].attach_price
          } else {
            list[i]['cheap'] = list[i].discount > 0.01 ? list[i].price - list[i].discount : 0
            list[i]['showMoney'] = list[i].discount > 0.01 ? list[i].discount : list[i].price
          }
          list[i].num = parseInt(list[i].num)
          // 是否选中该商品
          list[i]['pitch'] = true
          // 该商品的单价 * 数量
          list[i]['showCount'] = parseFloat(list[i].showMoney * list[i].num).toFixed(2)
          // 该商品的单价
          list[i].showMoney = parseFloat(list[i].showMoney).toFixed(2)
          // 该商品已优惠 * 数量
          list[i]['showCheap'] = list[i].cheap * list[i].num

          sumMoney += parseFloat(list[i].showCount)
          sumCount += parseInt(list[i].num)
          showCheap += parseFloat(list[i].showCheap)

        }

        this.setData({
          allCount: parseInt(sumCount),
          sumMoney: parseFloat(sumMoney).toFixed(2),
          sumCheap: parseFloat(showCheap).toFixed(2),
          shoppList: list
        })
      } else {
        wx.showToast({
          title: '请先登录哦！',
          icon: 'none',
          duration: 1300
        })
      }
    })
  },

  // 事件委托
  getUserInfo: function (e) {

    if (e.detail.userInfo && app.globalData.showLogin) {
      const self = this
      app.signin(e.detail, function (res) {
        app.globalData.showLogin = false
        self.setData({
          showLogin: false
        })
        self.goodsCart()
        // self.getCoupon()
      })
    }

  },

  // 去结算
  settlemen: function (e) {

    let list = this.data.shoppList

    let itemJson = []

    let isPitch = true

    for (let i = 0; i < list.length; i++) {

      // 把勾选中的商品放到缓存
      if (list[i].pitch) {
        isPitch = false
        itemJson.push(list[i])
      }

    }

    if (isPitch) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 1800
      })
      return
    }

    wx.setStorageSync('shoppList', itemJson)

    wx.navigateTo({
      url: '/pages/checkOrder/checkOrder',
    })
  },

  // 全选或取消全选
  allPitch: function () {

    let pitchFlag = this.data.allPitch ? false : true

    let count = 0
    let cheap = 0
    let allCount = 0

    for (let i = 0; i < this.data.shoppList.length; i++) {
      this.data.shoppList[i].pitch = pitchFlag

      if (pitchFlag) {
        allCount += parseInt(this.data.shoppList[i].num)
        cheap += parseFloat(this.data.shoppList[i].showCheap)
        count += parseFloat(this.data.shoppList[i].showCount)
      }
    }

    this.setData({
      allCount: parseInt(allCount),
      sumCheap: parseFloat(cheap).toFixed(2),
      sumMoney: parseFloat(count).toFixed(2),
      allPitch: pitchFlag,
      shoppList: this.data.shoppList
    })
  },

  // 选中或取消当前商品
  pitchCheck: function (e) {
    let cartId = e.currentTarget.dataset.cartid

    let count = parseFloat(this.data.sumMoney)
    let cheap = parseFloat(this.data.sumCheap)

    for (let i = 0; i < this.data.shoppList.length; i++) {

      if (this.data.shoppList[i].cart_id == cartId) {

        if (this.data.shoppList[i].pitch) {

          cheap -= parseFloat(this.data.shoppList[i].showCheap)
          count -= parseFloat(this.data.shoppList[i].showCount)
          this.setData({
            allCount: this.data.allCount - this.data.shoppList[i].num,
            sumCheap: parseFloat(cheap).toFixed(2),
            sumMoney: parseFloat(count).toFixed(2),
            [`shoppList[${i}].pitch`]: false
          })
          break

        } else {

          cheap += parseFloat(this.data.shoppList[i].showCheap)
          count += parseFloat(this.data.shoppList[i].showCount)
          this.setData({
            allCount: this.data.allCount + this.data.shoppList[i].num,
            sumCheap: parseFloat(cheap).toFixed(2),
            sumMoney: parseFloat(count).toFixed(2),
            [`shoppList[${i}].pitch`]: true
          })
          break

        }

      }

    }
  },

  // 删除商品
  clearCommodity: function (e) {
    let cartId = e.currentTarget.dataset.cartid

    for (let i = 0; i < this.data.shoppList.length; i++) {

      if (this.data.shoppList[i].cart_id == cartId) {

        axios('/groupon/removeGoodsCart', {
          cart_id: cartId,
          store_id: app.globalData.storeId,
          num: this.data.shoppList[i].num
        }).then(res => {
          if (res.data.resultcode == 1) {
            app.globalData.shoppCount = app.globalData.shoppCount - this.data.shoppList[i].num
            if (this.data.shoppList[i].pitch) {
              this.setData({
                allCount: this.data.allCount - this.data.shoppList[i].num,
                sumCheap: parseFloat(parseFloat(this.data.sumCheap) - parseFloat(this.data.shoppList[i].cheap * this.data.shoppList[i].num)).toFixed(2),
                sumMoney: parseFloat(parseFloat(this.data.sumMoney) - parseFloat(this.data.shoppList[i].showMoney * this.data.shoppList[i].num)).toFixed(2),
              })
            }

            this.data.shoppList.splice(i, 1)

            this.setData({
              shoppList: this.data.shoppList
            })

          }
        })

        break

      }

    }
  },

  // 数量减1
  subtractCount: function (e) {
    let cartId = e.currentTarget.dataset.cartid

    for (let i = 0; i < this.data.shoppList.length; i++) {

      if (this.data.shoppList[i].cart_id == cartId && this.data.shoppList[i].num > 1) {

        axios('/groupon/removeGoodsCart', {
          cart_id: cartId,
          store_id: app.globalData.storeId,
          num: 1
        }).then(res => {
          console.log(res)
          if (res.data.resultcode == 1) {
            --app.globalData.shoppCount
            if (this.data.shoppList[i].pitch) {
              this.setData({
                allCount: this.data.allCount - 1,
                sumCheap: parseFloat(parseFloat(this.data.sumCheap) - parseFloat(this.data.shoppList[i].cheap)).toFixed(2),
                sumMoney: parseFloat(parseFloat(this.data.sumMoney) - parseFloat(this.data.shoppList[i].showMoney)).toFixed(2),
              })
            }
            this.setData({
              [`shoppList[${i}].num`]: --this.data.shoppList[i].num,
              [`shoppList[${i}].showCheap`]: parseFloat(this.data.shoppList[i].showCheap - this.data.shoppList[i].cheap).toFixed(2),
              [`shoppList[${i}].showCount`]: parseFloat(this.data.shoppList[i].showCount - this.data.shoppList[i].showMoney).toFixed(2)
            })

          }
        })

        break

      }

    }

  },

  // 数量加1
  plusCount: function (e) {
    let cartId = e.currentTarget.dataset.cartid

    for (let i = 0; i < this.data.shoppList.length; i++) {

      if (this.data.shoppList[i].cart_id == cartId) {

        // 添加商品的数量不能超过库存
        if (this.data.shoppList[i].num >= this.data.shoppList[i].goods_stock) {
          wx.showToast({
            title: '暂无更多库存哦！',
            icon: 'none'
          })
          return
        }

        let paramJson = {
          goods_id: this.data.shoppList[i].goods_id,
          cart_id: cartId,
          store_id: app.globalData.storeId,
          num: 1
        }

        if (this.data.shoppList[i].attach_id) {
          paramJson['attach_id'] = this.data.shoppList[i].attach_id
        }

        axios('/groupon/optGoods', paramJson).then(res => {
          console.log(res)
          if (res.data.resultcode == 1) {
            ++app.globalData.shoppCount
            if (this.data.shoppList[i].pitch) {
              this.setData({
                allCount: this.data.allCount + 1,
                sumCheap: parseFloat(parseFloat(this.data.sumCheap) + parseFloat(this.data.shoppList[i].cheap)).toFixed(2),
                sumMoney: parseFloat(parseFloat(this.data.sumMoney) + parseFloat(this.data.shoppList[i].showMoney)).toFixed(2),
              })
            }
            this.setData({
              [`shoppList[${i}].num`]: ++this.data.shoppList[i].num,
              [`shoppList[${i}].showCheap`]: parseFloat(parseFloat(this.data.shoppList[i].showCheap) + parseFloat(this.data.shoppList[i].cheap)).toFixed(2),
              [`shoppList[${i}].showCount`]: parseFloat(parseFloat(this.data.shoppList[i].showCount) + parseFloat(this.data.shoppList[i].showMoney)).toFixed(2)
            })

          }
        })

        break

      }

    }
  },

  // 触摸事件，记录触摸起点
  touchstart: function (e) {

    let cartId = e.currentTarget.dataset.cartid

    this.setData({
      deleteCartId: cartId,
      showDel: false,
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY
    })
  },

  // 滑动事件
  touchmove: function (e) {
    let self = this,
      startX = self.data.startX,
      startY = self.data.startY,
      moveX = e.changedTouches[0].clientX,
      moveY = e.changedTouches[0].clientY;

    console.log(startX - moveX)

    if (startX - moveX > 50) {
      this.setData({
        showDel: true
      })
    } else {
      this.setData({
        showDel: false
      })
    }

  },

  // 查询优惠券
  // getCoupon: function () {
  //   axios('/groupon/coupons', {
  //     store_id: app.globalData.storeId
  //   }).then(res => {
  //     if (res.data.resultcode == 1) {
  //       this.setData({
  //         couponList: res.data.result.store
  //       })
  //     }
  //   })
  // },

  // 关闭优惠券模态框
  closeCoupon: function () {
    this.setData({
      couponState: false
    })
  },

  // 打开优惠券模态框
  openCoupon: function () {
    this.setData({
      couponState: true
    })
  },

  // 优惠券模态框阻止事件冒泡，此方法不能删
  stopCoupon: function () { },



  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})